<?php

namespace app\admin\controller\acitivity;

use app\admin\controller\Zlog;
use app\common\controller\Backend;
use fast\Tree;
use think\Config;
use think\Db;
use think\Exception;
use think\Session;

/**
 * 课程
 *
 * @icon fa fa-circle-o
 */
class Cate extends Backend
{
    
    /**
     * Cate模型对象
     * @var \app\admin\model\acitivity\Cate
     */
    protected $model = null;
    protected $orgName_tree = [];
    protected $org_list = [];
    protected $searchFields = 'name,mobile';
    protected $modelValidate = true;
    protected $modelSceneValidate = true;
    protected $current_info = [];
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\org\Orgcate;
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign('typeList', model('User')->getTypeList() );
        $this->orgcatelist = $this->model->getOrgCateList();
        $orgGradeModel = new \app\admin\model\org\Orggrade;
        $this->gradeList = $orgGradeModel->getGradeList();

        if(ORG_CATE_ID > 0){
            $org_where['parent_id|id'] = ORG_CATE_ID;
        }else{
            $org_where['level'] = array('in', array('1','2'));
        }
        $orgcateList = collection($this->model->where($org_where)->select())->toArray();
        $orgcat = [];
        $parent_ids = [];
        foreach($orgcateList as $k => $v){

            $orgcat[$v['id']] = $v['name'];
            $parent_ids[] = $v['id'];
        }
        $this->orgcat = $orgcat;
        $this->parent_ids = $parent_ids;
        Tree::instance()->init($orgcateList, 'parent_id');
        $this->org_list = $result = Tree::instance()->getTreeList(Tree::instance()->getTreeArray(0));
        $current = Db::name('org_cate')->where('id','=',ORG_CATE_ID)->find();
        $admin = Db::name('admin')->where('org_cate_id','=',ORG_CATE_ID)->order('id','asc')->limit(1)->select();
        $current['username'] = $admin[0]['username'];
        $current['avatar'] = $admin[0]['avatar'];
        $current['createtime'] = date('Y-m-s', $current['createtime']);
        $orgName_tree = [];
        foreach($result as $k => $v){
            $orgName_tree[$v['id']] = $v['name'];
        }
        $this->orgName_tree = $orgName_tree;
        $this->current_info = $current;
        $this->view->assign('org_cate_id', ORG_CATE_ID);
        $this->view->assign('current', $current);
        $this->view->assign('orgName_tree', $this->orgName_tree);
        $this->view->assign('orgcat', $this->orgcat);

    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    public function index(){

        if ($this->request->isAjax()) {
            if($this->request->request('keyField')){
                $data = $this->selectpage2();
                if(empty($data['list'])){
                    $data['list'] = array_merge([['id'=>0,'name'=>'总平台']], $data['list']);
                    $data['total'] = $data['total']+1;
                }
                return json($data);
            }
            if(ORG_CATE_ID > 0){
                $org_where['parent_id'] = ORG_CATE_ID;
                $ids1 = $this->model->where($org_where)->column('id');
                $ids2 = array();
                if($ids1){
                    $ids2 = $this->model->where('parent_id', 'in', $ids1)->column('id');
                }
                $ids = array_unique(array_merge($ids1, $ids2));
                $orgcateList = collection($this->model->where('id', 'in', $ids)->select())->toArray();
            }else{
                $org_where['level'] = array('in', array('1','2','3'));
                $orgcateList = collection($this->model->where($org_where)->select())->toArray();
            }
//            $orgcateList = collection($this->model->where($org_where)->select())->toArray();
            Tree::instance()->init($orgcateList, 'parent_id');
            $list = $result = Tree::instance()->getTreeList(Tree::instance()->getTreeArray(ORG_CATE_ID));
            $user_model = new \app\admin\model\User;
            foreach($list as $k => &$v){
                // 查询用户注册信息
                $where_user['org_cate_id'] = $v['id'];
                $where_user['user_auth_type'] = 0;
                $user_total_list = $user_model->where($where_user)->select();
                $user_total_list = collection($user_total_list)->toArray();
                // 查询当前单位所有的活跃数
                $reg_user_count = 0;
                $visitor_user_count = 0;

                foreach ($user_total_list as $ks => $vs) {
                    if($vs['user_type'] == 2){
                        $visitor_user_count++;
                    }else{
                        $reg_user_count++;
                    }
                }
                $list[$k]['reg_user_num'] = $reg_user_count;
                $list[$k]['visitor_user_num'] = $visitor_user_count;
                $v['pid'] = $v['parent_id'];
                if($v['parent_id'] == 0){
                    $list[$k]['parent_id'] = '顶级类别';
                }else{
                    $list[$k]['parent_id'] = $this->orgcat[$v['parent_id']];
                }
            }
            $total = count($this->org_list);
            $result = array("total" => $total, "rows" => $list, 'current'=>$this->current_info);
            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 查看家长学员
     */
    public function detail()
    {
        $org_cate_id = $this->request->param('ids');
        $this->view->assign("ids", $org_cate_id);

        $this->model = new \app\admin\model\acitivity\Item;
        //当前是否为关联查询
        $this->relationSearch = true;
        $this->searchFields = 'item.id,item.name';
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
//            $where2 = $this->getSelfDataWhere('item.org_cate_id');
            $total = $this->model
                ->with(["user"])
                ->where($where)
                ->where(['item.org_cate_id'=>$org_cate_id])
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->with(["user"])
                ->where($where)
                ->where(['item.org_cate_id'=>$org_cate_id])
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        return $this->view->fetch();
    }

    /*
   * 添加家长学员
   */
    public function itemadd()
    {
        $org_cate_id = $this->request->param('ids');
        $this->view->assign("ids", $org_cate_id);
        $this->model = new \app\admin\model\acitivity\Item;
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
//                $params['org_cate_id'] = ORG_CATE_ID;
                $params['user_id'] = Db::name('admin')->where('id', AID)->value('user_id');
                $result = $this->model->validate()->save($params);
                if ($result === false) {
                    $this->error($this->model->getError());
                }
                $this->success();
            }
            $this->error();
        }
        return $this->view->fetch();
    }

    /*
     * 编辑家长学员
     * @param null $ids
     * @return string
     */
    public function itemedit($ids = null)
    {
        $this->model = new \app\admin\model\acitivity\Item;
        $row_data = $this->model->get(['id' => $ids]);
        if (!$row_data) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $result = $row_data->validate()->save($params);
                if ($result === false) {
                    $this->error($row_data->getError());
                }
                $this->success();
            }
            $this->error();
        }
        $this->view->assign("row", $row_data);
        return $this->view->fetch();
    }

    /*
     * 删除家长学员
     * @param null $ids
     */
    public function itemdel($ids = null)
    {
        $this->model = new \app\admin\model\acitivity\Item;
        if ($ids) {
            $res = $this->model->where('id', 'in', $ids)->delete();
            if($res===false){
                $this->error($this->model->getError());
            }
            $this->success();
        }
        $this->error('编号错误！');
    }
}
